import { useRef, useState } from 'react';

import {
  equipmentAccessProtocolDeleteApi,
  equipmentAccessProtocolListApi,
  equipmentAccessProtocolSaveOrUpdateApi,
  type AccessProtocol,
} from '@/api/equipmentAccessProtocolApi';
import { type OperationType } from '@/constants';

import AccessProtocolAddForm from './modules/add';
import AccessProtocolCardList from './modules/CardList';

import type { ActionType } from '@ant-design/pro-components';

/**
 * 设备接入协议管理页面
 * 提供接入协议的创建、编辑、删除等功能，支持卡片式展示
 */
const EquipmentAccessProtocol = () => {
  // 表格操作引用
  const actionRef = useRef<ActionType>(null);

  // 表单实例
  const [form] = AForm.useForm();

  // 抽屉状态管理
  const [drawerShow, setDrawerShow] = useState(false);
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  const [currentRecord, setCurrentRecord] = useState<Partial<AccessProtocol>>({});

  // 加载状态
  const [submitLoading, setSubmitLoading] = useState(false);
  const [_loading, _setLoading] = useState(false);

  // 统计数据
  const [totalDeviceCount, setTotalDeviceCount] = useState(0);
  const [refreshTrigger, setRefreshTrigger] = useState(0); // 用于触发列表刷新

  /**
   * 获取接入协议列表数据
   * @param params 查询参数
   * @returns 格式化的表格数据
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      const { current = 1, pageSize = 10 } = params;
      const requestParams = {
        page: current,
        pageSize,
      };

      const res = await equipmentAccessProtocolListApi(requestParams);

      if (res.success && res.data) {
        const dataList = res.data.records || [];

        // 计算总设备数统计
        const totalCount = dataList.reduce(
          (sum: number, item: AccessProtocol) => sum + (item.deviceCount || 0),
          0
        );
        setTotalDeviceCount(totalCount);

        return {
          data: dataList,
          success: true,
          total: res.data.total || 0,
        };
      } else {
        window.$message.error(res.message || '获取协议列表失败');
        return {
          data: [],
          success: false,
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取接入协议列表失败:', error);
      window.$message.error('获取协议列表失败，请稍后重试');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  /**
   * 关闭抽屉并重置状态
   */
  const handleDrawerClose = () => {
    setCurrentRecord({});
    setDrawerType('ADD');
    setDrawerShow(false);
    form.resetFields();
  };

  /**
   * 编辑接入协议
   * @param record 协议记录
   */
  const handleEdit = (record: AccessProtocol) => {
    if (!record || !record.id) {
      window.$message.error('协议ID不存在，无法编辑');
      return;
    }

    setCurrentRecord(record);
    setDrawerType('EDIT');

    // 预填充表单数据
    setTimeout(() => {
      form.setFieldsValue({
        name: record.name,
        remark: record.remark,
        productCode: record.productCode,
      });
    }, 100);

    setDrawerShow(true);
  };

  /**
   * 删除接入协议
   * @param record 协议记录
   */
  const handleDelete = (record: AccessProtocol) => {
    // 参数验证
    if (!record || !record.id) {
      window.$message.error('删除失败：协议ID不存在');
      return;
    }

    const protocolName = record.name || '未知协议';

    AModal.confirm({
      title: '确认删除',
      content: `确定要删除协议${protocolName}吗？删除后不可恢复,请确保没有设备正在使用此协议！`,
      okText: '确认删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await equipmentAccessProtocolDeleteApi({ id: record.id });
          if (res.success) {
            window.$message.success('协议删除成功');
            // 触发列表刷新
            setRefreshTrigger(prev => prev + 1);
          } else {
            window.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除协议失败:', error);
          window.$message.error('删除失败，请稍后重试');
        }
      },
    });
  };

  /**
   * 处理表单提交
   * 支持新增和编辑两种模式
   */
  const handleSubmit = async () => {
    try {
      setSubmitLoading(true);

      const params = await form.validateFields();
      const requestParams = {
        ...currentRecord,
        ...params,
      };

      const res = await equipmentAccessProtocolSaveOrUpdateApi(requestParams);
      if (res.success) {
        const successMessage = drawerType === 'EDIT' ? '协议更新成功' : '协议创建成功';
        window.$message.success(successMessage);

        // 触发列表刷新
        setRefreshTrigger(prev => prev + 1);

        // 延迟关闭抽屉，确保用户看到成功提示
        setTimeout(() => {
          form.resetFields();
          handleDrawerClose();
        }, 300);
      } else {
        window.$message.error(res.message || '操作失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      if (error instanceof Error) {
        window.$message.error(`操作失败：${error.message}`);
      } else {
        window.$message.error('表单验证失败，请检查输入');
      }
    } finally {
      setSubmitLoading(false);
    }
  };

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <div className="page-main-title">泛协议接入</div>
        <div className="page-sub-title">
          泛协议接入允许用户通过自定义物模型结合定制实例的方式进行非标准协议的设备接入
        </div>
      </div>
      <div className="page-content-box">
        <div className="page-content show-bg">
          <div>
            <div className="flex justify-between items-center mb-4">
              <div className="text-lg font-bold">接入实例</div>
              <div className="text-sm text-gray-500">已接入设备总数：{totalDeviceCount}</div>
            </div>
          </div>
          {/* 实例列表卡片 */}
          <AccessProtocolCardList
            actionRef={actionRef}
            onEdit={handleEdit}
            onDelete={handleDelete}
            onAdd={() => {
              form.resetFields();
              setCurrentRecord({});
              setDrawerType('ADD');
              setDrawerShow(true);
            }}
            fetchData={fetchData}
            searchParams={{ refreshTrigger }}
          />
        </div>
      </div>
      {/* 新增/编辑抽屉 */}
      <ADrawer
        title={drawerType === 'ADD' ? '新增实例' : '编辑实例'}
        width={600}
        onClose={handleDrawerClose}
        open={drawerShow}
        footer={
          <div className="flex justify-end space-x-2">
            <AButton onClick={handleDrawerClose} disabled={submitLoading}>
              取消
            </AButton>
            <AButton type="primary" onClick={handleSubmit} loading={submitLoading}>
              确定
            </AButton>
          </div>
        }
      >
        <div className="w-full px-4 py-4">
          <AForm form={form} layout="vertical" labelAlign="right" labelCol={{ span: 24 }}>
            <AccessProtocolAddForm form={form} data={currentRecord} />
          </AForm>
        </div>
      </ADrawer>
    </div>
  );
};

export default EquipmentAccessProtocol;
